import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";
import { randomColor } from "@/const";

export default ({ value, type }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    console.log("value===", value);
    const legendData = [];
    value?.forEach((item, index) => {
      item &&
        item.sourceList[0]?.series &&
        legendData.push(item.sourceList[0]?.series);
    });

    const colors = legendData?.map((item) => {
      return {
        name: item,
        color: randomColor(),
      };
    });

    const series = value.map((item) => {
      const seriesData = item.sourceList.map((item) => {
        const current = colors.find((color) => color.name === item.series);
        return {
          name: item.series,
          value: [item.x * 1, item.y * 1],
          itemStyle: { color: current.color },
        };
      });

      return {
        name: item.sourceList[0]?.series,
        data: seriesData,
        symbolSize: 8, // 点的大小
        type: "scatter",
      };
    });

    const chart = echarts.init(chartRef.current);
    const option = {
      color: colors.map((color) => color.color),
      tooltip: {
        // https://echarts.apache.org/zh/option.html#tooltip
        show: true,
        trigger: "axis",
        // formatter: "总老化时间:{b} 松弛率:{c}",
        // formatter: function () { // https://echarts.apache.org/zh/option.html#tooltip.formatter
        //   return "y = 2x";
        // },
      },
      legend: {
        top: 10,
        type: "scroll", // https://echarts.apache.org/zh/option.html#legend.type
        data: legendData,
      },
      xAxis: {
        type: "value",
        // data: xAsisData,
        // name: value.sourceList[0]?.series, // https://echarts.apache.org/zh/option.html#xAxis.name
        nameLocation: "middle", // https://echarts.apache.org/zh/option.html#xAxis.nameLocation
        nameGap: 40, // https://echarts.apache.org/zh/option.html#xAxis.nameGap
      },
      yAxis: {
        type: "value",
        // name: type === "yl" ? "σ0.4" : "松弛率/%",
        nameLocation: "middle", // https://echarts.apache.org/zh/option.html#xAxis.nameLocation
        nameGap: 40, // https://echarts.apache.org/zh/option.html#xAxis.nameGap
      },
      series: series,
    };

    chart.setOption(option);

    return () => {
      chart.dispose(); // 清理 chart 实例
    };
  }, [value]);

  return <div ref={chartRef} style={{ width: "100%", height: 330 }}></div>;
};
